package com.knoya.chejian.pda.module.ruku

import android.app.ActivityManager
import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.media.SoundPool
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.AutoCompleteTextView
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import com.knoya.chejian.pda.R
import com.knoya.chejian.pda.activity.BaseActivity
import com.knoya.chejian.pda.minterface.OnUserDataInterface
import com.knoya.chejian.pda.module.zupan.ZupanBean
import com.knoya.chejian.pda.myadapter.ArrayAdapter
import com.knoya.chejian.pda.myadapter.RukuAdapter
import com.knoya.chejian.pda.util.FileUtils
import com.knoya.chejian.pda.util.JsonUtil
import com.knoya.chejian.pda.util.Myutil

import kotlinx.android.synthetic.main.activity_ruku.*
import kotlinx.android.synthetic.main.header_knoya.*
import org.json.JSONException
import org.json.JSONObject

class RukuActivity : BaseActivity(), View.OnClickListener, AdapterView.OnItemClickListener,
    View.OnFocusChangeListener {


    var issao = false
    lateinit var M : RukuM
    lateinit var dialog: AlertDialog
    lateinit var cangkus : ArrayList<String>
    lateinit var cangweis : ArrayList<String>
    lateinit var pcodes : ArrayList<RukuPcodeBean>
    lateinit var yuanpcodes : ArrayList<RukuPcodeBean>
    lateinit var rupcodes : ArrayList<RukuPcodeBean>
    lateinit var rukuadapter : RukuAdapter
    lateinit var cangkuadapter : ArrayAdapter<String>
    lateinit var cangweiadapter : ArrayAdapter<String>
    lateinit var cangkubean : RukuCangBeanList
    val chaxunfangshi = ArrayList<String>()
    var issaoyunxu = true
    var code = 1;
    override fun getLayoutId(): Int {
        when(jiemian){
            1 -> return R.layout.activity_ruku
            2 -> return R.layout.activity_ruku_2
        }
        return R.layout.activity_ruku
    }

    override fun initCreate() {
        code = intent.getIntExtra("code",1)
        cangkus = ArrayList<String>()
        cangweis = ArrayList<String>()
        pcodes = ArrayList<RukuPcodeBean>()
        yuanpcodes = ArrayList<RukuPcodeBean>()
        rupcodes = ArrayList<RukuPcodeBean>()
        cangkubean = RukuCangBeanList(cangkus,cangweis)
        M = RukuM()
        Bt_Ruku_Xiazai.setOnClickListener(this)
        Bt_Ruku_kaishi.setOnClickListener(this)
        Bt_ruku_ok.setOnClickListener(this)
        rukuadapter = RukuAdapter(pcodes,this)
        Lv_Ruku.adapter = rukuadapter
        cangkuadapter = ArrayAdapter(this@RukuActivity, android.R.layout.simple_dropdown_item_1line, cangkus)
        cangweiadapter = ArrayAdapter(this@RukuActivity, android.R.layout.simple_dropdown_item_1line, cangweis)
        At_Cangku.setAdapter(cangkuadapter)
        At_Cangwei.setAdapter(cangweiadapter)
        At_Cangwei.setOnClickListener(this)
        At_Cangku.setOnClickListener(this)
        At_Cangku.onItemClickListener = this
        At_Cangku.onFocusChangeListener = this
        At_Cangwei.onFocusChangeListener = this

        tv_header_title.isFocusable = true
        tv_header_title.isFocusableInTouchMode = true
        tv_header_title.requestFocus()
        tv_header_title.requestFocusFromTouch()
        if(code == 1){
            tv_header_title.text = "入库"
        }else if(code == 2){
            tv_header_title.text = "调仓"
        }
        iv_header_left.visibility = View.VISIBLE
        iv_header_left.setOnClickListener(this)

        mBoradcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if(!isAPPBroughtToBackground()){
                    return
                }
                if(!issaoyunxu){
                    return
                }
                if (intent.action == "nlscan.action.SCANNER_RESULT" && intent.hasExtra("SCAN_BARCODE1")) {
                    val scanResult_1 = intent.getStringExtra("SCAN_BARCODE1").trim()
                    samiaoOk(scanResult_1)
                }
                if(intent.action == "android.intent.ACTION_DECODE_DATA" && intent.hasExtra("barcode_string")){
                    val scanResult = intent.getStringExtra("barcode_string").trim()
                    samiaoOk(scanResult)
                }
            }
        }
        Et_Ruku_pcode.setOnEditorActionListener { _, actionId, _ ->
            var isOK = true
            isOK
        }
        chaxunfangshi.add("按订单")
        chaxunfangshi.add("按柜号")
        chaxunfangshi.add("按包号")
        when(jiemian){
            1 -> {
                val adapter = ArrayAdapter(this, R.layout.lv_sp_tvitem, chaxunfangshi)
                Sp_ruku_Chaxun.adapter = adapter
            }
            2 ->{
                val adapter = ArrayAdapter(this, R.layout.lv_sp_tvitem_2, chaxunfangshi)
                Sp_ruku_Chaxun.adapter = adapter
            }
        }
//        Et_Ruku_pcode.setText("B20081436-1-1/1-1GB)
    }

    //扫描获取到数据后处理
    fun samiaoOk(data : String){
        if(data.length>28){
            Myutil.tishidialog(this@RukuActivity,"条码扫描错误，请重新扫描")
            Myutil.zhendong(this)
            FileUtils.playSound(R.raw.baojing);
        }
        if(issao) {
            ispcodes(data)
            rukuadapter.notifyDataSetChanged()
        }else{
            Et_Ruku_pcode.setText(data)
        }
    }

    private fun ispcodes(pcode :String) {
        Log.d("TAAG",pcode)
        for (bean in rupcodes){
            if(pcode == bean.pcode){
                Myutil.MyTost("这包货已经扫描过")
                Myutil.zhendong(this)
                FileUtils.playSound(R.raw.baojing);
                return
            }
        }
        for (bean  in pcodes){
            if(pcode == bean.pcode){
                rupcodes.add(bean)
                pcodes.remove(bean)
                zongbaoshu()
                return
            }
        }
        issaoyunxu = false
        Myutil.tishidismissdialog(this, "没找到条码$pcode",object : DialogInterface.OnDismissListener{
            override fun onDismiss(dialog: DialogInterface?) {
                issaoyunxu = true
            }
        })
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        cangkubean.cangkudown(cangkus[position])
        Log.d("TAAAG",cangkubean.toString())
        cangweiadapter.notifyDataSetChanged()
        At_Cangwei.setText(cangweis[0])
    }

    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        Log.d("TAAAG",hasFocus.toString())
        when(v) {
            At_Cangwei -> {
                At_Cangwei.showDropDown()
            }
            At_Cangku -> {
                At_Cangku.showDropDown()
            }
        }
//
//        var view = v as AutoCompleteTextView
//        if (hasFocus) {
//            view.showDropDown ();
//        }
    }

    override fun onClick(v: View?) {
        when(v){
            iv_header_left-> {
                finish()
            }
            At_Cangku -> {
                At_Cangku.showDropDown()
            }
            At_Cangwei -> {
                At_Cangwei.showDropDown()
            }
            Bt_Ruku_kaishi -> {
                if(issao){
                    Bt_Ruku_kaishi.text = "开始入库"
                    issao = false
                    rupcodes.clear()
                    pcodes.clear()
                    for (bean in yuanpcodes){
                        pcodes.add(bean)
                    }
                }else{
                    issao = true
                    Bt_Ruku_kaishi.text = "停止入库"
                }
            }
            Bt_ruku_ok -> {
                if(rupcodes.size == 0){
                    Myutil.tishidialog(this,"录入条码后才能入库")
                    return
                }
                if(!issao){
                    Myutil.tishidialog(this,"开始入库后才能入库")
                    return
                }
                if(At_Cangku.text.toString().trim() == "" || At_Cangwei.text.toString().trim() == ""){
                    Myutil.tishidialog(this,"输入仓库和仓位后才能入库")
                    return
                }
                dialog = Myutil.showupdatedialog(this@RukuActivity, "正在入库", false)
                M.ruku(this,At_Cangku.text.toString().trim(),At_Cangwei.text.toString().trim(),rupcodes,object : OnUserDataInterface{
                    override fun onUserData(data: String?) {
                        if(data == null){
                            return
                        }
                        Log.d("TAAAG",data)
                        var status = ""
                        var msg = ""
                        try {
                            var jo = JSONObject(data)
                            status = JsonUtil.getvolue(jo,"status")
                            msg = JsonUtil.getvolue(jo ,"msg")
                        }catch (e : JSONException){
                            e.printStackTrace()
                        }
                        if(msg != ""){
                            Myutil.tishidialog(this@RukuActivity,msg)
                        }
                        dialog.dismiss()
                        if(status != "success"){
                            return
                        }
                        Bt_Ruku_kaishi.text = "开始入库"
                        issao = false
                        rupcodes.clear()
                        yuanpcodes.clear()
                        pcodes.clear()
                        Tv_tishi.text = ""
                        rukuadapter.notifyDataSetChanged()
                        dialog.dismiss()

                    }

                    override fun onNot(throwable: String?) {
                        Log.d("TAAAG",throwable.toString() )
                        dialog.dismiss()
                    }

                })
            }
            Bt_Ruku_Xiazai -> {
                dialog = Myutil.showupdatedialog(this@RukuActivity, "正在获取数据", false)
                M.getdata(this,Sp_ruku_Chaxun.selectedItem.toString(),Et_Ruku_pcode.text.toString().trim(),object : OnUserDataInterface {
                    override fun onUserData(data: String?) {
                        dialog.dismiss()
                        if(data == null){
                            return
                        }
                        Myutil.longlogshow("TAAAG",Myutil.decodeUnicode(data))
                        jsondata(data)
                    }

                    override fun onNot(throwable: String?) {
                        dialog.dismiss()
                        Log.d("TAAAG",throwable.toString())
                    }
                })
            }
        }
    }

    fun jsondata(data : String){
        yuanpcodes.clear()
        cangweis.clear()
        cangkus.clear()
        cangkubean.cangweis.clear()
        pcodes.clear()
        var status = ""
        var msg = ""
        try {
            var jo = JSONObject(data)
            status = JsonUtil.getvolue(jo,"status")
            var jscang = JsonUtil.getjsvolue(jo,"used_position_list")
            var js = JsonUtil.getjsvolue(jo,"data")
            msg = JsonUtil.getvolue(jo ,"msg")
            for(i in 0 until js.length()){
                var pcodejo = js[i] as JSONObject
                var bean = RukuPcodeBean()
                bean.pcode = JsonUtil.getvolue(pcodejo,"pcode")
                bean.status_name = JsonUtil.getvolue(pcodejo,"status_name")
                bean.warehouse = JsonUtil.getvolue(pcodejo,"warehouse")
                bean.position = JsonUtil.getvolue(pcodejo,"position")
                yuanpcodes.add(bean)
            }
            for (i in 0 until jscang.length()){
                var cangjo = jscang[i] as JSONObject
                cangkubean.add(JsonUtil.getvolue(cangjo,"warehouse"),JsonUtil.getvolue(cangjo,"position"))
            }
        }catch (e : JSONException){
            e.printStackTrace()
            Log.d("TAAG",e.toString())
        }

        if(status == "success"){
            for (bean in yuanpcodes){
                pcodes.add(bean)
            }
            rukuadapter.notifyDataSetChanged()
            cangkubean.cangkuclean()
            Log.d("TAAAG",cangkubean.toString())
            cangkuadapter.notifyDataSetChanged()
            cangweiadapter.notifyDataSetChanged()
            if(cangkus.size > 0){
                At_Cangku.setText(cangkus[0])
                cangkubean.cangkudown(cangkus[0])
                At_Cangwei.setText(cangweis[0])
            }
        }else if(status == "error"){
        }
        zongbaoshu()
        if(msg != ""){
            Myutil.tishidialog(this,msg)
        }
        dialog.dismiss()
    }

    private fun zongbaoshu(){
        var dairuku = 0
        var yisaomiao = 0
        var daisaomiao = 0
        yisaomiao = rupcodes.size
        for (bean in yuanpcodes){
            if("初始" == bean.status_name){
                dairuku++
            }
        }
        daisaomiao = dairuku - yisaomiao
        Tv_tishi.text = "待入库： "+dairuku+" 未扫秒:"+daisaomiao+" 已扫描："+yisaomiao
    }

    fun isAPPBroughtToBackground(): Boolean {
        val am = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val tasks = am.getRunningTasks(1)
        if (!tasks.isEmpty()) {
            val topActivity = tasks[0].topActivity
            if (topActivity.className == this.javaClass.name) {

                return true
            }
        }
        return false
    }

}